package com.dcr.config;

import com.dcr.biz.IPersonalCenterBiz;
import com.dcr.entity.PersonalCenter;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.HashSet;
import java.util.Set;

//授权
public class CustomRealm extends AuthorizingRealm {
    @Autowired
    private IPersonalCenterBiz personalCenterBiz;
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        System.out.println("执行授权");
        //获取用户对象
        Subject subject = SecurityUtils.getSubject();
        PersonalCenter currentPersonalCenter = (PersonalCenter) subject.getPrincipal();
//        String username = (String) SecurityUtils.getSubject().getPrincipal();
        //创建授权信息
        SimpleAuthorizationInfo authorizationInfo = new SimpleAuthorizationInfo();
        Set<String> permission = new HashSet<>();
        if(currentPersonalCenter.getRole().equals("管理员")){
            permission.add("user:admin");
        }
        permission.add("user:user");


        authorizationInfo.setStringPermissions(permission);

        return authorizationInfo;
    }
    //认证
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
        System.out.println("执行认证");
        String username = (String) authenticationToken.getPrincipal();
        String password = new String((char[])authenticationToken.getCredentials());

        PersonalCenter personalCenter=personalCenterBiz.queryUserByUsername(username);

           //return Result.ok(personalCenter);

        //String realPwd = "123";
        if(personalCenter == null){
            throw new AccountException("账号不存在");
        }
        return new SimpleAuthenticationInfo(personalCenter,personalCenter.getPassword(),getName());
    }
}
